package cn.com.shaom.learning.sb.data.multi.config;

import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * ClassName: MultiDataSourceConfig
 * Description: 自定义多数据源
 * Date: 2018/1/2 14:45 【需求编号】
 *
 * @author Shaom
 * @version V1.0.0
 */
@Configuration
@EnableTransactionManagement
public class MultiDataSourceConfig {

    /* 第一个数据源配置 */
    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource-one")
    public DataSource oneDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JdbcTemplate oneJdbcTemplate() {
        return new JdbcTemplate(oneDataSource());
    }

    @Bean(name = "oneTransaction")
    public DataSourceTransactionManager oneTransaction() {
        DataSourceTransactionManager txName = new DataSourceTransactionManager();
        txName.setDataSource(oneDataSource());
        return txName;
    }

    /* 第2个数据源配置 */
    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource-two")
    public DataSource twoDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JdbcTemplate twoJdbcTemplate() {
        return new JdbcTemplate(oneDataSource());
    }

    @Bean(name = "twoTransaction")
    public DataSourceTransactionManager twoTransaction() {
        DataSourceTransactionManager txName = new DataSourceTransactionManager();
        txName.setDataSource(twoDataSource());
        return txName;
    }
}
